

<template>
  <div class="main-container">
    <el-dialog v-model="dialogFormVisible" v-if="dialogFormVisible" title="添加知识库" width="58%">
      <Add :departmentdata="departmentdata" :typeData="typeData" :userinfo="userinfo" :reviewData="reviewData" :knowledgeForm="knowledgeForm" @addSubmit="handleSubmit"></Add>
    </el-dialog>
    <el-dialog v-model="dialogFormEditVisible" v-if="dialogFormEditVisible" title="修改知识库" width="58%">
      <Update :departmentdata="departmentdata" :typeData="typeData" :userinfo="userinfo" :reviewData="reviewData" v-model:knowledgeForm="knowledgeForm" @updateSubmit="handleUpdateSubmit"></Update>
    </el-dialog>
    <el-dialog v-model="dialogFormCreateReviewVisible" title="发起审核" width="58%">
      <CreateReView  v-if="dialogFormCreateReviewVisible && typeData.length && reviewData.length && userinfo.length" :departmentdata="departmentdata" :typeData="typeData" :userinfo="userinfo" :reviewData="reviewData" v-model:reviewRecordsData="reviewRecordsData" @createReviewSubmit="handleCreateReviewSubmit"></CreateReView>
    </el-dialog>
    <el-dialog v-model="dialogFormRunReviewVisible" title="审核" width="58%">
      <RunReview  v-if="dialogFormRunReviewVisible && typeData.length && reviewData.length && userinfo.length" :departmentdata="departmentdata" :typeData="typeData" :userinfo="userinfo" :reviewData="reviewData" v-model:reviewRecordsData="reviewRecordsData" @runReviewSubmit="handleRunReviewSubmit"></RunReview>
    </el-dialog>
    <div class="table-actions">
      <el-button type="primary" v-permission="{ menuId, action: 'create' }" @click="handleAdd">新增</el-button>
      <el-button type="warning"  v-permission="{ menuId, action: 'update' } "@click="handleEdit">修改</el-button>
      <el-button type="danger"  :disabled="isStartReviewDisabled" v-permission="{ menuId, action: 'delete' }" @click="handleCreateReview">发起审核</el-button>
      <el-button type="danger"  :disabled="isReviewDisabled" v-permission="{ menuId, action: 'delete' }" @click="handleRunReview">审核</el-button>
      <el-button @click="resetDateFilter">重置日期筛选</el-button>
      <el-button @click="clearFilter">重置筛选</el-button>
    </div>
    <el-table ref="tableRef" v-loading="loading" element-loading-text="数据加载中..." row-key="id"
  :current-row-key="selectedRowId" border v-if="tableData.length && reviewData.length && userinfo.length && typeData.length" :data="tableData" style="width: 100%;height: 50%;" highlight-current-row=true
      @row-click="handleRowClick"
     >
      <el-table-column prop="id" label="id" min-width="50"/>
      <el-table-column prop="code" label="知识编号" min-width="120"/>
      <el-table-column prop="title" label="知识标题" min-width="120"/>
      <el-table-column prop="content" label="知识概述" min-width="200"/>
      <el-table-column prop="typeId" label="知识类别" min-width="120">
      <template #default="scope">
        <span>
          {{ findNodeById(typeData,scope.row.typeId)}}
        </span>
      </template>
      </el-table-column>
      <el-table-column prop="submitterId" label="提交人" min-width="100">
       <template #default="scope">
            <!-- 通过逗号连接数组中的成员用户名 -->
            <span>
              {{ getUserLabel(scope.row.submitterId) }}
            </span>
          </template>
      </el-table-column>
      <el-table-column prop="reviewerId" label="审核人" min-width="100">
          <template #default="scope">
            <!-- 通过逗号连接数组中的成员用户名 -->
            <span>
              {{ getReviewLabel(scope.row.reviewerId,scope.row.reviewGroupId) }}
            </span>
          </template>
        </el-table-column>
      <el-table-column prop="reviewGroupId" label="审核组" min-width="120" >
          <template #default="scope">
            <!-- 通过逗号连接数组中的成员用户名 -->
            <span>
              {{ getReviewGroupLabel(scope.row.reviewGroupId) }}
            </span>
          </template>
        </el-table-column>
      <el-table-column prop="status" label="知识状态" min-width="120">
        <template #default="scope">
          <!-- 使用 statusData 来映射状态 -->
          <span>
            {{ getStatusLabel(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" min-width="130" />
      <el-table-column prop="updateAt" label="更新时间" min-width="130"/>
      <el-table-column prop="publishedAt" label="发布时间" min-width="130"/>
      <el-table-column prop="docPath" label="文档路径" min-width="160"/>
      <el-table-column label="操作" fixed="right" width="300">
        <template #default="scope"> <!-- 通过插槽的scope 来绑定行数据 scope.row可以获取到当前行的数据 --->
          <el-button type="primary" size="mini" @click="handleEditRow(scope.row)">RAG推送</el-button>
          <!--<el-button type="primary" size="mini" v-permission="{ menuId, action: 'create' }" @click="handleEditRow(scope.row)">编辑</el-button>-->
          <el-button type="danger" size="mini"   v-permission="{ menuId, action: 'delete' }" @click="handelDelRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="selectedRow" class="detail-box">
      <h3>知识标题：{{ selectedRow.code }}</h3>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="知识库编辑" name="markdown">
          <!-- 硬件详情组件或展示区域 -->
        <div style="display: flex; height: 100%;">
          <el-tree
              v-if="knowledgeFileList.length"
              ref="treeRef"
              :data="knowledgeFileList"
              :props="{
                label: 'filePath',  // 使用 knowledgeCode 作为节点的 label 显示
                children: 'children'
              }"
              node-key="id"
              highlight-current
              @node-click="handleFileClick"
              :default-checked-keys="defaultCheckedKeys"
              style="width: 250px; border-right: 1px solid #ddd; padding: 8px; overflow-y: auto;"
            />
          <div style="flex: 1; display: flex; flex-direction: column; padding: 8px; overflow: hidden;">
            <MarkDownEidtor :disabled="isEditorDisabled" v-if="activeTab === 'markdown'" :modelValue="formattedMarkdown" :toolbars="customToolbars" @save="handleSave" style="flex: 1; overflow-y: auto;"/>
          </div>
          </div>
        </el-tab-pane>
         <el-tab-pane label="审核记录" name="reviewrecord">
          <ReviewRecords v-if="activeTab === 'reviewrecord' && reviewData.length > 0 && userinfo.length > 0" :reviewData="reviewData" :knowledgeData="selectedRow" :userinfo="userinfo" />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  
</template>
<script lang="ts" setup>
import { ref,reactive,onMounted,toRefs,computed,onBeforeMount,nextTick } from "vue"
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getKnowledgeInfoHandler,addKnowledgeInfoHandler,delKnowledgeInfoHandler,updateKnowledgeInfoHandler,getKnowledgeReviewGroupInfoHandler,getKnowledgeTypeInfoHandler,addKnowledgeReviewRecordsInfoHandler,updateKnowledgeReviewRecordsInfoHandler } from "../../api/knowledge.js"
import {getDepartmentList} from "../../api/department.js"
import MarkDownEidtor from "./tabs/MarkDownEidtor.vue"
import { getUsersAllList } from "../../api/user.js"
import Add from "./Add.vue"
import Update from "./Update.vue"
import CreateReView from "./CreateReview.vue"
import ReviewRecords from "./tabs/ReviewRecords.vue"
import RunReview from "./RunReview.vue"
const tableData = ref([])
const treeRef=ref(null)
const loading = ref(true)
const defaultCheckedKeys=ref([])
// 新增知识库模态框控制
const dialogFormVisible = ref(false)
// 修改知识库模态框控制
const dialogFormEditVisible = ref(false)
// 发起审核模态框控制
const dialogFormCreateReviewVisible = ref(false)
const dialogFormRunReviewVisible = ref(false)
const searchCriteria = reactive({
        username: '',
        password: '',
        ad_user_id: ''
      })

const route = useRoute()
const menuId = route.meta.menuId
const customToolbars = [
  'bold', 'italic', 'strikeThrough', '|',
  'title', 'quote', 'unorderedList', 'orderedList', '|',
  'link', 'image', 'table', '|',
  'save'  // ✅ 默认保存按钮
]
const knowledgeForm = reactive({
  "id": null,
  "code": "",
  "title": "",
	"content": "",
	"typeId": null,
	"submitterId": null,
	"reviewerId": null,
	"reviewGroupId": null,
	"status": null,
	"publishedAt": null,
	"docPath": ""
})

const reviewRecordsData = reactive({
   "id": null,
  "code":"",
  "reviewGroupId": null,
  "reviewerList": [],
  "reviewerId": null,
  "reviewTime": "",
  "reviewEndTime": null,
  "rejectReason": "",
  "approveReason": "",
  "reviewStatus": null,
})
const data = reactive({
  statusData: [
    {"value": 0,
    "label": "草稿"},
    {"value": 1,
    "label": "审核中"},
    {"value": 2,
    "label": "已发布"},
    {"value": 3,
    "label": "驳回"},
    {"value": 4,
    "label": "归档"},
  ],
  // 知识数据更新时格式，serviceType指定更新的类型，UpdateKnowledgeMd更新知识条目中文件名称和md文件内容，UpdateKnowledge 仅更新知识条目的属性内容
  updateData: {
    "serviceType": "",
    "MdExtra": {},
    "Extra": {},
  },
  reviewData: [],
  userinfo: [],
  typeData: [],
  knowledgeFileList: [],
})
const selectedRowId = ref(null)
const {statusData,updateData,reviewData,userinfo,typeData,knowledgeFileList}=toRefs(data)
const isStartReviewDisabled = computed(() => {
  if (!selectedRow.value) return true; // 没有选中行时禁用
  const status = selectedRow.value.status;
  // 发起审核按钮禁用条件
  return status === 4 || status === 1 || status === 2 ; // 审核中或待审核状态不能发起审核
});

const isReviewDisabled = computed(() => {
  if (!selectedRow.value) return true; // 没有选中行时禁用
  const status = selectedRow.value.status;
  // 审核按钮禁用条件
  return status !== 1; // 只有待审核状态可以执行审核
});
const isEditorDisabled = computed(() => {
  if (!selectedRow.value) return true; // 没有选中行时禁用
  const status = selectedRow.value.status;
  // 审核按钮禁用条件
  return status === 1 || status === 2; // 只有待审核状态可以执行审核
});
const filteredData = ref([])
const departmentdata= ref([])
const disabledUserId = ref("1")
const currentRow = ref(null)
const getStatusLabel =(statusValue) => {
    // 根据状态值查找标签
    const status = statusData.value.find(item => item.value=== statusValue);
    return status ? status.label : '未知';  // 如果没有找到对应值，返回 '未知'
}

const getReviewLabel=(reviewuserId,reviewGroupId)=>{
    console.log("usersWithIds================20250925",reviewData.value,"aaa==========",reviewuserId)
    const usersWithId3 = reviewData.value.flatMap(group => 
      group.users.filter(user => user.userId == reviewuserId && user.reviewGroupId==reviewGroupId))
    // 用 Map 去重，key 为 userId
    // const uniqueUsers = Array.from(new Map(usersWithId3.map(u => [u.userId, u])).values())
    return usersWithId3.map(u => u.personname).join(', ')
    // console.log("=============20250925=====usersWithId3========",usersWithId3)
}
const getReviewGroupLabel=(reviewGroupId)=>{
    console.log("reviewGroupId================20250925",reviewData.value,"aaa==========",reviewGroupId)
    
    const groupWithId3 = reviewData.value.find(item => item.id===reviewGroupId)
    return groupWithId3.name
}
const getUserLabel=(submitterId)=>{
    console.log("userinfo================20250925==========================",userinfo.value,"aaa==========",submitterId)
    const groupWithId3 = userinfo.value.find(item => item.id===submitterId)
    return groupWithId3.personname
}

const findNodeById=(tree, id)=> {
  for (const node of tree) {
    if (node.id === id) {
      return node.typeName
    }
    // 如果有 children，递归继续找
    if (node.children && node.children.length > 0) {
      const found = findNodeById(node.children, id)
      if (found) {
        return found
      }
    }
  }
  return null
}
const filterTableData=()=>{
  filteredData.value = tableData.value.filter(item => {
    return (
      (!searchCriteria.username || item.Username.includes(searchCriteria.username)) &&
      (!searchCriteria.password || item.Password.includes(searchCriteria.password)) &&
      (!searchCriteria.ad_user_id || item.Ad_user_id.includes(searchCriteria.ad_user_id))
    )
  })
}
// 添加知识库
const handleAdd = () =>{
  
  //addUserHandler(data).then((response)=>{
  //    console.log("response=========:",response.data)
  //})
  //const data=await getDepartmentData()
  //console.log("data++++++++++++++++++++++++++++",data)
  //departmentdata.value=data
  dialogFormVisible.value=true
   // knowledgeForm.publishedAt = new Date()
  console.log("department---------0807----------------")

}
// 修改知识库
const handleEdit =()=>{
   if (!selectedRow.value) {
    return console.warn("请先选择一行再修改")
  }
  console.log("修改这一行：", selectedRow.value)
  knowledgeForm.value={...selectedRow.value}
  dialogFormEditVisible.value=true

}
// 打开发起审核的模态框
const handleCreateReview = ()=>{
  if (!selectedRow.value) {
    return console.warn("请先选择一行再修改")
  }
  console.log("修改这一行：", selectedRow.value)
  knowledgeForm.value={...selectedRow.value}
   Object.assign(reviewRecordsData, {
    code: selectedRow.value.code,
    reviewGroupId: selectedRow.value.reviewGroupId,
    reviewerList: [],
    reviewerId: null,
    reviewTime: "",
    reviewEndTime: null,
    rejectReason: "",
    approveReason: "",
    reviewStatus: null,
  })
  console.log("=====================20250930---------------------------",reviewRecordsData)
  dialogFormCreateReviewVisible.value=true

}
// 打开审核的模态框
const handleRunReview = ()=>{
  if (!selectedRow.value) {
    return console.warn("请先选择一行再操作")
  }
  console.log("修改这一行：", selectedRow.value)
  knowledgeForm.value={...selectedRow.value}
   Object.assign(reviewRecordsData, {
    code: selectedRow.value.code,
    reviewGroupId: selectedRow.value.reviewGroupId,
    reviewerList: [],
    reviewerId: null,
    reviewTime: "",
    reviewEndTime: null,
    rejectReason: "",
    approveReason: "",
    reviewStatus: selectedRow.value.status,
  })
  console.log("=====================20251013---------------------------",reviewRecordsData)
  dialogFormRunReviewVisible.value=true
}

const handelDelRow=async(row)=>{
    try {
        
        await ElMessageBox.confirm(
          `确认要删除【${row.code}】吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        console.log("id=======20250929",row.id)
        const intId = Number(row.id)
        const response = await delKnowledgeInfoHandler(intId)
        
        if (response.data) {
            ElMessage({
                    message: response.data.message,
                    type: 'success',
            })
            console.log("delcategoryData==========20250929",response.data)
            await getKnowledgeInfo()
            
        }
    } catch(error) {
        console.error("删除失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "删除失败，请重试",
                    type: 'error',
        })
        // throw err // 如果需要让调用方知道错误
    }
    
}

// 获取知识库信息
const getKnowledgeInfo=async ()=>{
  try {
      const response=await getKnowledgeInfoHandler()
      if (response?.data?.data){
        const result = response.data.data
        const queryData = result.queryData
        // const decodedBytes = atob(base64String);
        // 将字节串转换为 Uint8Array
        // const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
        // 使用 TextDecoder 解码为字符串
        // const decoder = new TextDecoder("utf-8");
        // const decodedString = decoder.decode(uint8Array);
        console.log("queryData",queryData)
        // window.localStorage.setItem("menus",decodedString)
        // const md5Hash = md5(decodedString+'menus_list');
        // window.localStorage.setItem("md5Hash",md5Hash)

        // 存储菜单数据到 localStorage
        // const decodedString = window.localStorage.getItem('menus');
        // tableData.value = JSON.parse(decodedString)
        tableData.value = queryData
        
        if (filteredData.value.length==0) {
          filteredData.value = tableData.value
        } else {
          filterTableData()
        }
        selectedRowId.value = selectedRowId.value || tableData.value[0]?.id
        loading.value=false
        // 返回解析后的菜单数据
        //return JSON.parse(decodedString);
      }
  } catch(error){
    console.log(error)
  }  
}

// 获取部门数据
  const getDepartmentData=()=>{
      getDepartmentList().then((response)=>{
        const result = response.data.data
        if (result.queryData == '[]') {
                return [];
        } else {
            const base64String = result.queryData
            const decodedBytes = atob(base64String);
            // 将字节串转换为 Uint8Array
            const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
            // 使用 TextDecoder 解码为字符串
            const decoder = new TextDecoder("utf-8");
            const decodedString = decoder.decode(uint8Array);
            console.log("departmentinfo===========+++++++++",decodedString)
            //window.localStorage.setItem("menus",decodedString)
            //const md5Hash = md5(decodedString+'menus_list');
            //window.localStorage.setItem("md5Hash",md5Hash)     
            departmentdata.value=JSON.parse(decodedString)
            //console.log("departmentinfo=======---------------------====+++++++++",departmentdata)
            // 存储菜单数据到 localStorage
            // const decodedString = window.localStorage.getItem('menus');
            // 返回解析后的菜单数据
            // return JSON.parse(decodedString);
        }
      })
  }
// 清空userForm表单数据
const clearassetForm = () => {
  Object.keys(assetForm).forEach(key => {
    userForm[key] = "";
  });
};

// 定义接收事件的函数
const handleSubmit = async (formData) => {
  try {
    // 在父组件中执行相应的逻辑，例如提交数据到后端
    console.log('接收到的表单数据：', formData);
    // 创建一个新对象，排除 "password" 属性
    // const { checkpass, ...newformData } = formData;
    // console.log("newformData=============",newformData)
    // newformData["department_name"]=newformData["department_name"].toString();
    const response = await addKnowledgeInfoHandler(formData)
    if (response?.data) {
       ElMessage({
            message: response.data.message,
            type: 'success',
          })
       await getKnowledgeInfo()
    } else {
      ElMessage({
            message: response.data.message,
            type: 'Error',
      })
    }
    dialogFormVisible.value=false
    console.log("assetForm=====+++++++",assetForm)
    clearUserForm()
    console.log("assetForm=====+++++++",assetForm)
    // 可以在这里做API请求等操作
    
  } catch(error){
    console.log(error)
  }
};

// 定义接收更新事件的函数
const handleUpdateSubmit = async (formData) => {
  try {
    // 在父组件中执行相应的逻辑，例如提交数据到后端
    console.log('接收到的表单数据：', formData.value);
    updateData.value.serviceType="UpdateKnowledge"
    updateData.value.Extra={...formData.value}

    const response = await updateKnowledgeInfoHandler(formData.value.id,updateData.value)
    if (response?.data) {
       ElMessage({
            message: response.data.message,
            type: 'success',
          })
       await getKnowledgeInfo()
    } else {
      ElMessage({
            message: response.data.message,
            type: 'Error',
      })
    }
    dialogFormEditVisible.value=false
    console.log("assetForm=====+++++++",assetForm)
    clearUserForm()
    console.log("assetForm=====+++++++",assetForm)
    // 可以在这里做API请求等操作
    
  } catch(error){
    console.log(error)
  }
};
const handleCreateReviewSubmit  = async (formData) => {
  try {
    console.log("======================20251011==========",formData)
    formData.reviewStatus=1
    const response = await addKnowledgeReviewRecordsInfoHandler(formData)
    if (response?.data) {
       ElMessage({
            message: response.data.message,
            type: 'success',
          })
       await getKnowledgeInfo()
       dialogFormCreateReviewVisible.value=false
    } else {
      ElMessage({
            message: response.data.message,
            type: 'Error',
      })
    }
  } catch(error){
    console.log(error)
  }
  
}
const handleRunReviewSubmit  = async (formData) => {
  try {
    console.log("======================20251011==========",formData)
    // formData.reviewStatus=1
    const response = await updateKnowledgeReviewRecordsInfoHandler(formData.id,formData)
    if (response?.data) {
       ElMessage({
            message: response.data.message,
            type: 'success',
          })
       await getKnowledgeInfo()
       dialogFormRunReviewVisible.value=false
    } else {
      ElMessage({
            message: response.data.message,
            type: 'Error',
      })
    }
  } catch(error){
    console.log(error)
  }
  
}
// 模拟模板数据
const templateData = ref({
  title: '示例标题',
  section1_title: '第一个章节',
  section2_title: '第二个章节'
})
// 定义后端数据
const backendContent = ref('');
// 预定义的 Markdown 模板，使用占位符
const markdownTemplate = `
# {{ title }}

这是一个预定义模板，包含了一些占位符。

## {{ section1_title }}
这里是第一个部分的内容，可以添加任何你想要的内容。

## {{ section2_title }}
这是第二个部分的内容，可以继续编辑。
`

// 格式化模板，替换占位符为实际数据
const formattedMarkdown = computed(() => {
  if (backendContent.value && backendContent.value.trim() !== '') {
    // 后端有内容，替换占位符
    return backendContent.value
      .replace('{{ title }}', templateData.value.title)
      .replace('{{ section1_title }}', templateData.value.section1_title)
      .replace('{{ section2_title }}', templateData.value.section2_title);
  } else {
    // 后端没有内容，使用默认模板
    return markdownTemplate
      .replace('{{ title }}', templateData.value.title)
      .replace('{{ section1_title }}', templateData.value.section1_title)
      .replace('{{ section2_title }}', templateData.value.section2_title);
  }
});

const selectedRow = ref(null)
const activeTab = ref('markdown')

// 处理行点击事件
const handleRowClick = async (row) => {
  try {
    const rep = await getKnowledgeInfoHandler(row.id);
    if (rep?.data?.data) {
      const result = rep.data.data;
      const queryData = result.queryFile;
      console.log("queryData", queryData);

      // 将数据格式化为 el-tree 需要的格式
      knowledgeFileList.value = queryData.map(item => ({
        ...item,
        children: []  // 添加空的 children 数组以适应 el-tree 的要求
      }));

      // 等待 DOM 更新
      await nextTick();

      // 确保 treeRef 渲染完成且不为空
      if (treeRef.value) {
        const lastNodeId = knowledgeFileList.value.at(-1)?.id;
        let lastNode = {};
        if (lastNodeId) {
          treeRef.value.setCurrentKey(lastNodeId);  // 设置当前选中的节点
          // 根据 lastNodeId 查找节点内容
          lastNode = knowledgeFileList.value.find(item => item.id === lastNodeId);
          // 点击文件节点
          await handleFileClick(lastNode); // 直接传递 lastNode
        }
      } else {
        console.error("treeRef is null, el-tree not rendered yet");
      }

      // 设置当前选中的行
      selectedRow.value = row;
      console.log("selectedRow", selectedRow.value);

      // 激活 "markdown" 标签
      activeTab.value = 'markdown';
    }
  } catch (error) {
    console.log(error);
  }
};

// 切换tab方法
const handleTabClick =async(tab)=>{
  console.log('当前选中 tab:', tab.props.name)
  console.log("当前选中行selectRow",selectedRow.value)
  // 激活 tab 标签
  activeTab.value = tab.props.name;
}
// 点击知识文档，来调用知识文档接口，返回文档内容，加载到富文本编辑器中
const handleFileClick = async (node) => {
  try {
    if (!node?.filePath) {
      console.error('节点缺少 filePath');
      return;
    }

    // 获取点击节点的 filePath 或 id
    const filePath = node.filePath;  // 假设节点数据中有 filePath 字段
    const id = node.id;  // 假设节点数据中有 id 字段

    console.log('点击的节点信息:', node);

    // 基于 filePath 或 id 发起请求，获取该文件的详细内容
    const rep = await getKnowledgeInfoHandler("",filePath,"");
    if (rep?.data?.data) {
      const fileContent = rep.data.data.fileContent;
      const actualContent = fileContent[0];
      backendContent.value = actualContent;
    }
  } catch (error) {
    console.error('加载文件内容失败:', error);
  }
};
// 更新内容的方法
//const updateContent = (content) => {
//  selectedRow.value.content = content
//  console.log('更新后的内容：', content)
// }

// 保存内容的回调
const handleSave = async (content) => {
  try {
    console.log('保存内容：', content);
    const rowid = selectedRow.value.id;
    const updatedata = selectedRow.value;
    updateData.value.serviceType="UpdateKnowledgeMd"
    updateData.value.MdExtra["code"]=selectedRow.value.code
    updateData.value.MdExtra["contentMd"]=content
    updateData.value.MdExtra["docPath"]=selectedRow.value.docPath
    updateData.value.Extra={...selectedRow.value}
    console.log("========================rowid====20250916=====", rowid);
    console.log("========================updatedata====20250916=====", updateData.value);
    
    const response = await updateKnowledgeInfoHandler(rowid, updateData.value);

    if (response?.data?.message) {
      ElMessage({
        message: response.data.message,
        type: 'success',
      });
      await getKnowledgeInfo()
    } else {
      ElMessage({
        message: "操作成功，但未返回详细消息",
        type: 'success',
      });
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: error?.response?.data?.message || "添加失败，请重试",
      type: 'error',
    });
  }
};

const loadTypeData = async()=>{
    try {
        const response = await getKnowledgeTypeInfoHandler()
        if (response.data.data) {
            // typeData.value = base64Decode(response.data.data.queryData)
            typeData.value =response.data.data.queryData
            console.log("categoryData==========20250926",typeData.value)
        }
    }
    catch(error){
        console.error("保存配置失败:", err)
        ElMessage({
                    message: error?.response?.data?.message || "查询失败，请重试",
                    type: 'error',
        })
    }
}
const loadConfig = async()=>{
  try {
      const response = await getKnowledgeReviewGroupInfoHandler()
      console.log("response==============20250924",response.data.data)
      if (response.data.data) {
          // categoryData.value = base64Decode(response.data.data.assetCategory)
          reviewData.value = response.data.data.knowledgereviewData
          console.log("reviewData==========20250924",reviewData.value)
      }
  }
  catch(error){
      console.error("保存配置失败:", error)
      
  }
}

const fetchUserData = async () => {
  try {
    const response = await getUsersAllList()
    if (response.data.data) {
      const base64String = response.data.data.userlist
      const decodedBytes = atob(base64String);
      // 将字节串转换为 Uint8Array
      const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
      // 使用 TextDecoder 解码为字符串
      const decoder = new TextDecoder("utf-8");
      const decodedString = decoder.decode(uint8Array);
      console.log("userinfo=============20250924", decodedString)

      // 解析 decodedString 为 JSON 对象或数组
      userinfo.value = JSON.parse(decodedString);
      console.log("formuserinfo=============20250924", userinfo.value)
    }
  } catch (error) {
    console.error("获取用户失败:", error)
    ElMessage({
      message: error?.response?.data?.message || "查询失败，请重试",
      type: 'error',
    })
  }
}
onMounted(async ()=>{
  await getKnowledgeInfo()
  await getDepartmentData()
})
onBeforeMount(async ()=>{
  await fetchUserData()
  await loadTypeData()
  await loadConfig()
})



</script>
<style scoped>
.main-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.el-table {
  flex: 1;
}
.detail-box {
  flex: 1;
  padding: 16px;
  border-top: 1px solid #eee;
  background: #f9f9f9;
  overflow-y: auto;
}
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.search-input {
  margin-left: 10px;
  width: 300px;
}
.table-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;

}

</style>
